var layerLoad;
var layerDetailsId;
/**
 * 页面初始化加载
 */
(function(){
	initSystemAminds(1);
	initRolesList();
	$("#system-admin-form-update").attr("action",$api.admin.updateAmind).attr("method","POST");
})();
function initSystemAminds(currentPage){
    /*if($('#adminsSarchName').val()===""){
        var systemaAdmin = {
            currentPage : currentPage,
            pageSize : 10,
            searchName: $('#adminsSarchName').val()
        };
    }else{
        var systemaAdmin = {
            currentPage : currentPage,
            pageSize : 10,
            username: $('#adminsSarchName').val()
        };
	}*/
    var systemaAdmin = {
        currentPage : currentPage,
        pageSize : 10,
        username: $('#adminsSarchName').val()
    };

	$.ajax({
		url : $api.admin.selectSystemAdmins,
		type : "POST",
		dataType : "JSON",
		contentType : 'application/json',
		data : JSON.stringify(systemaAdmin),
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
            //外层的超级管理员标识
			if(window.parent.superFlog !== 1){
                data.msg.flog='false';
                console.log(data.msg.flog)
				$("#email").attr("disabled",'disabled');
                $("#isEnabled").attr("disabled",'disabled');
                $(".passwordBox").remove();
				$("#saveBtn").html("<button type='button' class='am-btn am-btn-primary' id='system-admin-update-close'>关闭</button>");
			}else{
                data.msg.flog="true";
			}
			layui.use('laytpl', function() {
				var laytpl = layui.laytpl;
				laytpl(systemAdmin.innerHTML).render(data, function(html) {
					$('#admin-body').html(html)
				});
			});
			layui.use('laypage', function() {
				layui.laypage({
					cont: $('#system-admin-page'),
					pages: data.totalPage,
					groups: 2,
					curr: data.currentPage,
					skip: true,
					jump: function (obj,first) {
						if(!first){
							initSystemAminds(obj.curr);
						}
					}
				});
			});
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
}
/**
 * 后台管理人员角色 -- 查询
 */
function initRolesList(){
	$.ajax({
		url : $api.role.selectAllRoles,
		type : "GET",
		dataType : "JSON",
		data : {
		},
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
			var roleOptionHtml = '';
			$(data.msg).each(function (index,dom){
               //roleOptionHtml +="<label class='am-checkbox-inline radio'><input type='checkbox' sort = "+ index +" name='checkbox' value="+dom.id+">"+dom.name+"</label>" ;
                if(dom.id == 7 || dom.id == 10 || dom.id == 11){
                    roleOptionHtml +="<label class='am-checkbox-inline radio'><input type='radio' sort = "+ index +" name='checkbox' value="+dom.id+">"+dom.name+"</label>" ;
				}else{
                    roleOptionHtml +="<label class='am-checkbox-inline'><input type='checkbox' sort = "+ index +" name='checkbox' value="+dom.id+">"+dom.name+"</label>" ;
                }
			});
			$('#roleId').html(roleOptionHtml);
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
};
/**
 * 搜索
 */
$('#sys-product-form-list-search').submit(function(e){
	e.preventDefault();
	initSystemAminds(1);
});

/**
 * 详情查询
 */
$('#admin-body').on('click','.btn-system-admin-update',function(){
	$.ajax({
		url : $api.admin.selectSystemAdminById,
		type : "POST",
		dataType : "JSON",
		data : {
			"adminId" : $(this).attr('id')
		},
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data,e) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
            Selected("#roleId input",data.msg.rolesStr);
			$("#orderId").val(data.msg.id);
			$('#username').val(data.msg.username);
			$('#name').val(data.msg.name);
            $('#phone').val(data.msg.phone);
			$('#email').val(data.msg.email);
			if(data.msg.isEnabled){
				$("#isEnabled").prop("selectedIndex", 0).attr("selected","selected" );
			}else{
				$("#isEnabled").prop("selectedIndex", 1).attr("selected","selected" );
			}
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
	layerDetailsId = layer.open({
		type : 1,
		title : '管理员详情',
		area : 'auto',
		maxWidth : '1000px',
		content : $('#system-admin-update-model'),
	});
	$("#layer-details-id").val(layerDetailsId);
});

/**
 * 保存
 */
$("#system-admin-update-submit").on("click", function(){
	var flog=0;
    $("#roleId input").each(function(index,dom){
    	if($(dom)[0].checked===true){
            if($(dom).val()==='7'||$(dom).val()==='11'||$(dom).val()==='10'){
                flog++
            }
		}
    });
    console.log(flog);
	if(flog > 1){
        layer.msg('仅能为一类配送人员', {icon: 2});
        return
	}
	var domArr =$("#system-admin-form-update").serializeArray();
	var dataAjax={};
    var checkboxTxt='';
	$.each(domArr,function(index,data){
		data.name === "checkbox" ? index===0 ? checkboxTxt=data.value : checkboxTxt+=','+data.value : dataAjax[data.name]=data.value;
	});
    dataAjax["name"]=$("#name").val();
    dataAjax["rolesStr"]=checkboxTxt;
    dataAjax["isEnabled"] = (dataAjax["isEnabled"] =="1");
    if($("#password").val()===$("#passwordSecond").val()){
        delete dataAjax["passwordSecond"];
        if($("#password").val()===""){
            delete dataAjax["password"];
		}
	}else{
        layer.msg('密码不一致', {icon: 2});
    	return
	}
    $.ajax({
        url : $api.admin.insertOrUpdateAdmin,
        type : "POST",
        dataType : "JSON",
        contentType : 'application/json',
        data : JSON.stringify(dataAjax),
        beforeSend : function () {
            layerLoad = layer.load();
        },
        success : function(data) {
			if(!$checkRemouteStatus(data)){
			layer.close(layerLoad);
			return;
		}
		layer.close(layerLoad);
		layer.close($("#layer-details-id").val());
		$("#password").val("");
		$("#passwordSecond").val("");
		layer.msg('操作成功', {icon: 1});
		initSystemAminds(1);
        },
        error : function() {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });

});
/*关闭*/
$("#system-admin-update-model").on("click","#system-admin-update-close", function(){
	layer.close(layerDetailsId);
});

/*checked回显*/
function Selected(domTxt,dataTxt){
    var productCategoryIds=dataTxt.split(",");
    $(domTxt).each(function(index,dom){
        if(productCategoryIds.indexOf($(dom).val())!== -1){
            $(dom)[0].checked=true;
        }else{
            $(dom)[0].checked=false;
        }
    });
};